﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Com.CMS263.Util
{
    /// <summary>
    /// 用来解析标签的类
    /// </summary>
    public class TagUtil
    {


        /// <summary>
        /// 得到指定标签所包含的内容
        /// </summary>
        /// <param name="ctx">包含标签的内容</param>
        /// <param name="tagName">标签的名字不含</param>
        /// <returns></returns>
        public List<string> GetTag(string ctx, string tagName, List<string> tagList)
        {
            if (ctx.IndexOf("<" + tagName) >= 0)
            {
                int start = ctx.IndexOf("<" + tagName);

                int end = ctx.IndexOf("</" + tagName + ">") + tagName.Length + 3;
                string test = ctx.Substring(start, end - start);
                tagList.Add(ctx.Substring(start, end - start));
                int endindex = end + 1;
                if (ctx.Length > endindex)
                {
                    string subHtml = ctx.Substring(endindex);
                    if (subHtml.IndexOf("<" + tagName) >= 0)
                    {
                        GetTag(subHtml, tagName, tagList);
                    }
                }


            }
            return tagList;

        }
        /// <summary>
        /// 将一组字符串拆成键值对
        /// </summary>
        /// <param name="tagHtml"></param>
        /// <returns></returns>
        public Dictionary<string, string> Getattribute(string tagHtml)
        {

            List<string> attrList = new List<string>();
            Dictionary<string, string> attr = new Dictionary<string, string>();
            string[] arr = tagHtml.Split(' ');
            //得到所有属性的字符串
            foreach (string str in arr)
            {
                if (str.Replace(" ", "") != "")
                {
                    attrList.Add(str);
                }
            }
            //拆分属性字符串，得到键值对
            foreach (string str in attrList)
            {
                if (str.Split('=').Length > 1)
                {
                    attr[str.Split('=')[0].ToLower()] = str.Split('=')[1];
                }
            }

            return attr;
        }
        /// <summary>
        /// 取得某个标签中间的html到吗
        /// </summary>
        /// <param name="tag">标签</param>
        /// <param name="ctx">包含标签的html代码</param>
        /// <returns></returns>
        public string GetInnerHTML(string tag, string ctx)
        {
            int start = ctx.IndexOf(">");
            int end = ctx.IndexOf("</" + tag + ">");
            if (end > start)
            {
                return ctx.Substring(start + 1, end - start - 1);
            }
            else
            {
                return null;
            }
        }
    }
}
